package edu.zut.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ServletDemo2", urlPatterns = "/demo2",initParams = {@WebInitParam(name = "key",value = "v")})
public class ServletDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取一个ServletContext对象   这个对象是全局唯一，被所有用户以及servlet对象共享的
        ServletContext context = this.getServletContext();
        //先去获取统计访问次数的计算器，如果获取到，我们直接+1，如果获取不到，直接设置一个
        Integer count = (Integer) context.getAttribute("count");
        if (count == null) {
            count = 1;
        } else {
            count ++;
        }
        //获取servletConfig对象
        ServletConfig config = this.getServletConfig();
        String servletName = config.getServletName();
        System.out.println("servletName = " + servletName);
        String v = config.getInitParameter("key");
        System.out.println("v = " + v);

        context.setAttribute("count",count);
        response.getWriter().write("访问次数："+count);

    }
}
